//
//  GHSStockViewController.m
//  penzer
//
//  Created by 还带大道 on 2018/11/14.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "GHSStockViewController.h"
#import "SPSelectScrollView.h"
#import "SPSliderScrollView.h"
#import "GHSSellingViewController.h"
#import "GHSNotSaleViewController.h"
#import "GHSStockWarningViewController.h"
#import "GHSStockBottomView.h"
#import "GHSTabBarController.h"
#import "GHSStockFilterView.h"

@interface GHSStockViewController ()<UIScrollViewDelegate>
@property (nonatomic,weak) UIView *searchBar;
@property (nonatomic,weak) SPSelectScrollView *topScrollView;
@property (nonatomic,strong) CAGradientLayer *gl;
@property (nonatomic,weak) SPSliderScrollView *bottomScrollView;
@property (nonatomic,strong) GHSStockBottomView *bottomEditView;
@property (nonatomic,strong) GHSStockFilterView *filterView;
@property (nonatomic,weak) UIButton *btn_nav_left;
@property (nonatomic,weak) UIButton *btn_nav_right;
@property (nonatomic,assign) NSInteger cureentPage;
@property (nonatomic,assign) BOOL edit;
@property (nonatomic,assign) BOOL selectAll;

@end

@implementation GHSStockViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"库存管理";
    _cureentPage = 0;
    [self setupUI];
}


- (void)setupUI
{
    [self setupNavRightBtn];
    [self setupSearchBar];
    [self setupTopView];
    [self setupBottomView];
    [self.topScrollView selectedWithIndex:0];
}


- (void)setupNavRightBtn
{
    UIButton *btn_left = [[UIButton alloc] init];
    _btn_nav_left = btn_left;
    btn_left.backgroundColor = [UIColor clearColor];
    [btn_left addTarget:self action:@selector(leftBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [btn_left setImage:[UIImage imageNamed:@"编辑"] forState:UIControlStateNormal];
    [btn_left setImage:[UIImage imageNamed:@"选中 copy 2"] forState:UIControlStateSelected];
    [btn_left setTitle:@"编辑" forState:UIControlStateNormal];
    [btn_left setTitle:@"完成" forState:UIControlStateSelected];
    [btn_left setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn_left setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    btn_left.titleLabel.font = [UIFont systemFontOfSize:15];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn_left];
    
    UIButton *btn_right = [[UIButton alloc] init];
    _btn_nav_right = btn_right;
    btn_right.backgroundColor = [UIColor clearColor];
    [btn_right addTarget:self action:@selector(rightBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [btn_right setImage:[UIImage imageNamed:@"筛选"] forState:UIControlStateNormal];
    [btn_right setImage:[UIImage imageNamed:@"筛选"] forState:UIControlStateSelected];
    [btn_right setTitle:@"筛选" forState:UIControlStateNormal];
    [btn_right setTitle:@"收起" forState:UIControlStateSelected];
    [btn_right setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn_right setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    btn_right.titleLabel.font = [UIFont systemFontOfSize:15];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn_right];
    
}


- (void)setupSearchBar
{
    UIView *searchBar = [UIView new];
    _searchBar = searchBar;
    searchBar.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:searchBar];
    [searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(60);
    }];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"搜索  (1)"] forState:UIControlStateNormal];
    [btn setTitle:@"搜索" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(onClickSearch) forControlEvents:UIControlEventTouchUpInside];
    btn.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:15];
    [btn setTitleColor:RZ_COLOR(219, 219, 219) forState:UIControlStateNormal];
    btn.layer.cornerRadius = 17.5;
    btn.layer.borderColor = RZ_COLOR_ALPHA(0, 0, 0, 0.1).CGColor;
    btn.layer.borderWidth = 1;
    [searchBar addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(35);
        make.center.equalTo(searchBar);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
    }];
    
}




- (void)setupTopView
{
    SPSelectScrollView *topScrollView  = [SPSelectScrollView new];
    _topScrollView = topScrollView;
    [self.view addSubview:topScrollView];
    [topScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.searchBar.mas_bottom);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(45);
    }];
    
    self.topScrollView.backgroundColor = [UIColor whiteColor];
    NSArray *item = @[@"在售商品",@"未上架",@"库存预警"];
    self.topScrollView.btnOnClickBlock = ^(NSInteger index) {
        [self topBtnOnClickWithIndex:index];
    };
    
    self.topScrollView.indicatorBar_height = 4;
    self.topScrollView.item_textColor_nomal = RZ_COLOR(137, 136, 139);
    self.topScrollView.item_textColor_selected = RZ_COLOR(89, 11, 195);
    self.topScrollView.item_font_nomal = [UIFont fontWithName:@"PingFangSC-Medium" size:15];
    self.topScrollView.item_font_selected = [UIFont fontWithName:@"PingFangSC-Semibold" size:15];
    self.topScrollView.firstItem_leftMargin = 0;
    self.topScrollView.item_margin = 0;
    self.topScrollView.item_inset = 5;
    self.topScrollView.average = YES;
    self.topScrollView.items = item;
    
    
    //为指示条添加渐变色
    CALayer *layer = self.topScrollView.indicatorBar.layer;
    CAGradientLayer *gl = [CAGradientLayer layer];
    _gl = gl;
    gl.frame = layer.bounds;
    gl.startPoint = CGPointMake(0, 0);
    gl.endPoint = CGPointMake(1, 1);
    gl.colors = @[(__bridge id)RZ_COLOR(48, 35, 174).CGColor,(__bridge id)RZ_COLOR(200, 109, 215).CGColor];
    gl.locations = @[@(0),@(1.0f)];
    [layer addSublayer:gl];
    
    layer.shadowColor = RZ_COLOR(238, 217, 255).CGColor;
    layer.shadowOffset = CGSizeMake(0,2);
    layer.shadowRadius = 6;
    layer.shadowOpacity = 1;
    self.gl.cornerRadius = self.topScrollView.indicatorBar_height*0.5;
    layer.shadowPath = [UIBezierPath bezierPathWithRect:layer.bounds].CGPath;
    
}


- (void)setupBottomView
{
    SPSliderScrollView *sliderV = [SPSliderScrollView new];
    _bottomScrollView = sliderV;
    [self.view addSubview:sliderV];
    sliderV.scrollViewDidEndDeceleratingBlock = ^(NSInteger cureentPage) {//滚动了
        [self.topScrollView selectedWithIndex:cureentPage];
    };
    [sliderV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topScrollView.mas_bottom).offset(15);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    NSArray<NSString *> *classNames = @[@"GHSSellingViewController",@"GHSNotSaleViewController",@"GHSStockWarningViewController"];
    NSMutableArray<UIView *> *views = [NSMutableArray array];
    [classNames enumerateObjectsUsingBlock:^(NSString * _Nonnull className, NSUInteger idx, BOOL * _Nonnull stop) {
        UIViewController *vc = [NSClassFromString(className) new];
        if(vc){
            [self addChildViewController:vc];
            [views addObject:vc.view];
        }
    }];
    sliderV.views = views;
    
}



#pragma mark--点击了顶部切换按钮
- (void)topBtnOnClickWithIndex:(NSInteger)index
{
    RZLog(@"----%ld",index);
    _gl.frame = self.topScrollView.indicatorBar.layer.bounds;
    [self.bottomScrollView selectedWithPage:index animateWithDuration:0];
    _cureentPage = index;
    //刷新数据
    [self refreshWithIndex:index];
}



#pragma mark--切换页面后的刷新数据
- (void)refreshWithIndex:(NSInteger)index
{
    if(index <self.childViewControllers.count)
    switch (index) {
        case 0:{//在售商品
            GHSSellingViewController *selling = self.childViewControllers[index];
            selling.selectBlock = ^(NSInteger totalCount, NSInteger selectedCount) {
              self.bottomEditView.descL.text = [NSString stringWithFormat:@"共%ld件商品",selectedCount];
                self.bottomEditView.allSelectBtn.selected = (totalCount==selectedCount);
            };
            selling.edit = _edit;
            selling.selectAll = _selectAll;
            [self.bottomEditView.rightBtn setTitle:@"下架" forState:UIControlStateNormal];
            self.bottomEditView.rightBtn_W.constant = 50;
            break;
        }
        case 1:{//未上架
            GHSNotSaleViewController *notSale = self.childViewControllers[index];
            notSale.selectBlock = ^(NSInteger totalCount, NSInteger selectedCount) {
                self.bottomEditView.descL.text = [NSString stringWithFormat:@"共%ld件商品",selectedCount];
                self.bottomEditView.allSelectBtn.selected = (totalCount==selectedCount);
            };
            notSale.edit = _edit;
            notSale.selectAll = _selectAll;
            [self.bottomEditView.rightBtn setTitle:@"上架" forState:UIControlStateNormal];
            self.bottomEditView.rightBtn_W.constant = 50;
            break;
        }
        case 2:{//库存预警
            GHSStockWarningViewController *sw = self.childViewControllers[index];
            sw.selectBlock = ^(NSInteger totalCount, NSInteger selectedCount) {
                self.bottomEditView.descL.text = [NSString stringWithFormat:@"共%ld件商品",selectedCount];
                self.bottomEditView.allSelectBtn.selected = (totalCount==selectedCount);
            };
            sw.edit = _edit;
            sw.selectAll = _selectAll;
            [self.bottomEditView.rightBtn setTitle:@"增加库存" forState:UIControlStateNormal];
            self.bottomEditView.rightBtn_W.constant = 60;
            break;
        }
    }
}




#pragma mark--搜索
- (void)onClickSearch
{
    RZLog(@"onClickSearch");
}


#pragma mark--编辑
- (void)leftBtnOnClick:(UIButton *)btn
{
    if(!self.btn_nav_right.isSelected){//未选中筛选，可编辑
        btn.selected = !btn.isSelected;
        _edit = btn.isSelected;
        if(!_edit){//退出编辑取消全选
            _selectAll = NO;
        }
        self.bottomEditView.hidden = !_edit;
        self.bottomEditView.allSelectBtn.selected = _selectAll;
#warning 编辑状态不允许进行切换界面操作
        self.topScrollView.scrollView.userInteractionEnabled = !_edit;
        self.bottomScrollView.scrollView.scrollEnabled = !_edit;
        [self refreshWithIndex:_cureentPage];
    }
}



#pragma mark--筛选
- (void)rightBtnOnClick:(UIButton *)btn
{
    if(!self.btn_nav_left.isSelected){//未选中编辑,可筛选
        btn.selected = !btn.isSelected;
        self.filterView.hidden = !btn.isSelected;
    }
}



#pragma mark--删除
- (void)delete
{
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"确认要删除该商品吗？" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ac_delete = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self editViewActionWithStatusIsDelete:YES];
    }];
    
    UIAlertAction *ac_cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertC addAction:ac_delete];
    [alertC addAction:ac_cancel];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alertC animated:YES completion:nil];
    });
}



#pragma mark--下架\上架\增加库存\删除
- (void)editViewActionWithStatusIsDelete:(BOOL)isDelete
{
    switch (self.cureentPage) {
        case 0:{// 下架\删除
            GHSSellingViewController *selling = self.childViewControllers[_cureentPage];
            if(isDelete){
                [selling deleteGoodsComplete:^(BOOL res) {
                    RZLog(@"删除%@",res?@"成功":@"失败");
                }];
            }else{
                [selling pullOffShelfGoodsComplete:^(BOOL res) {
                    RZLog(@"下架%@",res?@"成功":@"失败");
                }];
            }
            break;
        }
        case 1:{// 上架\删除
            GHSNotSaleViewController *notSale = self.childViewControllers[_cureentPage];
            if(isDelete){
                [notSale deleteGoodsComplete:^(BOOL res) {
                    RZLog(@"删除%@",res?@"成功":@"失败");
                }];
            }else{
                [notSale putOnShelfGoodsComplete:^(BOOL res) {
                    RZLog(@"上架%@",res?@"成功":@"失败");
                }];
            }
            break;
        }
        case 2:{// 增加库存\删除
            GHSStockWarningViewController *sw = self.childViewControllers[_cureentPage];
            if(isDelete){
                [sw deleteGoodsComplete:^(BOOL res) {
                    RZLog(@"删除%@",res?@"成功":@"失败");
                }];
            }else{
                [sw addGoodsStockComplete:^(BOOL res) {
                   RZLog(@"增加库存%@",res?@"成功":@"失败");
                }];
            }
            break;
        }
    }
}





#pragma mark--setter&&getter

- (GHSStockFilterView *)filterView
{
    if(!_filterView){
        _filterView = [GHSStockFilterView shareView];
        __weak typeof(self) weakS = self;
        _filterView.itemOnClickBlock = ^(NSInteger index) {
            RZLog(@"index=%ld",index);
            [weakS rightBtnOnClick:weakS.btn_nav_right];
        };
        [RZ_KEYWINDOW addSubview:_filterView];
        [_filterView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(kTopHeight);
            make.bottom.left.right.mas_equalTo(0);
        }];
    }
    return _filterView;
}


- (GHSStockBottomView *)bottomEditView
{
    if(!_bottomEditView){
        _bottomEditView = [GHSStockBottomView shareView];
        _bottomEditView.hidden = YES;
        _bottomEditView.backgroundColor = [UIColor whiteColor];
        GHSTabBarController *tab = (GHSTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        _bottomEditView.frame = tab.customTabBar.bounds;
        [tab.customTabBar addSubview:_bottomEditView];
        
        __weak typeof(self) weakS = self;
        _bottomEditView.onClickAllBlock = ^(BOOL selected) {//是否全选
            weakS.selectAll = selected;
            [weakS refreshWithIndex:weakS.cureentPage];
        };
        
        _bottomEditView.onClickLeftItemBlock = ^{
            [weakS delete];
        };
        _bottomEditView.onClickRightItemBlock = ^{
            [weakS editViewActionWithStatusIsDelete:NO];
        };
    }
    return _bottomEditView;
}


@end

